package com.aiyige.page.my.settings.acount;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventChangePhoneNumberSuccess;
import com.aiyige.model.ChangePhoneNumberModel;
import com.aiyige.model.SmsCode;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.page.login.callbacks.ITimerCallBack;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.VerifyCodeManager;
import com.aiyige.utils.widget.VerifyCodeInputView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.vondear.rxtools.RxDataTool;
import com.vondear.rxtools.RxTool;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 修改手机号（输入新手机）
 * xiachao
 */
@Route(path = ARouterConfig.ChangePhoneNumberInputPage)
public class ChangePhoneNumberInputPage extends BaseActivity implements ITimerCallBack {


    @BindView(R.id.et_mobile)
    EditText etMobile;
    @BindView(R.id.widget_verify_code)
    VerifyCodeInputView widgetVerifyCode;
    @BindView(R.id.btn_send_verify_code)
    Button btnSendVerifyCode;
    @BindView(R.id.btn_next)
    Button btnNext;

    SmsCode smsCode;
    @Autowired
    String code;

    boolean sending = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_change_phone_number_input);
        ButterKnife.bind(this);
        initTitleLayout("");
        ARouter.getInstance().inject(this);
        widgetVerifyCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkInput();
            }
        });
        widgetVerifyCode.setHint("");
        VerifyCodeManager.getInstance().addLoginCallBack(this);
        fillViews();
    }

    private void checkInput() {
        boolean isNull = true;
        if (!isEmpty(getVerifyCode())
                && getVerifyCode().length() == 6) {
            isNull = false;
        }
        btnNext.setEnabled(!isNull);
    }


    public String getVerifyCode() {
        return widgetVerifyCode.getVerifyCode();
    }


    private void fillViews() {

    }

    private String getPhone() {
        return etMobile.getText().toString();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        VerifyCodeManager.getInstance().removeLoginCallBack(this);
    }

    @Override
    public void onTick(long l) {
        //防止计时过程中重复点击
        btnSendVerifyCode.setClickable(false);
        btnSendVerifyCode.setText((l / 1000) + "s");
        btnSendVerifyCode.setTextColor(ContextCompat.getColor(this, R.color.zwcolor_gray_b1b5c1));
    }

    @Override
    public void onFinish() {
        btnSendVerifyCode.setTextColor(ContextCompat.getColor(this, R.color.zwcolor_black_111111));
        //重新给Button设置文字
        btnSendVerifyCode.setText(getResources().getString(R.string.get_verification_code));
        //设置可点击
        btnSendVerifyCode.setClickable(true);
    }

    private void sendVerifyCode() {
        if (RxDataTool.isNullString(getPhone())) {
            ToastX.show(MyApp.getInstance().getString(R.string.phone_can_not_empty));
            return;
        }
        if (sending) {
            return;
        }

        VerifyCodeManager.getInstance().tCaptchaDialog(this, new VerifyCodeManager.TCaptchaCallBack() {
                    @Override
                    public void success() {
                        sending = true;
                        ApiManager.getService().fetchByMobile(getPhone(), "changeMobileNew").enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) {
                                sending = false;
                                try {
                                    if (response.isSuccessful()) {
                                        smsCode = JsonUtil.toObject(response.body().string(), SmsCode.class);
                                        VerifyCodeManager.getInstance().start();
                                    } else {
                                        ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                                        onFailure(call, new Throwable(data.getMessage()));
                                    }
                                } catch (Exception e) {
                                    try {
                                        onFailure(call, new Throwable(e.toString()));
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                    }
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                sending = false;
                                if (t != null) {
                                    ToastX.show(t.getMessage());
                                }
                            }
                        });
                    }

                    @Override
                    public void failed() {

                    }
                }
        );


    }

    private void doChange() {
        if (TextUtils.isEmpty(getPhone())) {
            ToastX.show(getResources().getString(R.string.phone_can_not_empty));
            return;
        }
        if (isNull(getVerifyCode())) {
            ToastX.show(MyApp.getInstance().getString(R.string.enter_your_verification_code));
            return;
        }
        if (getVerifyCode().length() < 6) {
            ToastX.show(MyApp.getInstance().getString(R.string.verify_code_incomplete));
            return;
        }
        String oldMobile = AccountUtil.getMobile() == null ? "" : AccountUtil.getMobile();
        if (smsCode != null && !TextUtils.isEmpty(getPhone()) && !TextUtils.isEmpty(getVerifyCode()) && smsCode.getMobile().equals(getPhone()) && RxTool.Md5(getVerifyCode()).equals(smsCode.getCode())) {
            ChangePhoneNumberModel changePhoneNumberModel = ChangePhoneNumberModel.newBuilder()
                    .newCode(getVerifyCode())
                    .newMobile(smsCode.getMobile())
                    .oldCode(code)
                    .oldMobile(oldMobile)
                    .build();
            ApiManager.getService().changeMobile(changePhoneNumberModel).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) {
                    try {
                        if (response.isSuccessful()) {
//                        smsCode = JsonUtil.toObject(response.body().string(), SmsCode.class);
                            // 验证并更新手机号
                            VerifyCodeManager.getInstance().cancel();
                            ARouter.getInstance().build(ARouterConfig.ChangePhoneNumberSuccessPage).withString("mobile", smsCode.getMobile()).navigation();
                            EventBus.getDefault().post(new EventChangePhoneNumberSuccess());
                            finish();
                        } else {
                            ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                            onFailure(call, new Throwable(data.getMessage()));
                        }
                    } catch (Exception e) {
                        try {
                            onFailure(call, new Throwable(e.toString()));
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    if (t != null) {
                        ToastX.show(t.getMessage());
                    }
                }
            });
        } else {
            ToastX.show("手机号或验证码不正确");
        }


    }


    @OnClick({R.id.btn_send_verify_code, R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_send_verify_code:
                sendVerifyCode();
                break;
            case R.id.btn_next:
                doChange();
                break;
        }
    }
}
